﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunergyLogic;
using System.Web.Security;
using System.Globalization;
using System.Web.UI.DataVisualization.Charting;
using System.Text;

public partial class meter_MeterDaily : System.Web.UI.Page
{
    int meterId;

    communergyEntities db = new communergyEntities();
    ElectricityMeter meter = null;
    protected void Page_Load(object sender, EventArgs e)
    {   
        bool requestValid;
        MembershipUser thisUser = Membership.GetUser();

        if (thisUser != null)
        {
            var userId = thisUser.ProviderUserKey;
            var meterIdString = Request.QueryString["meterId"];
            meter = Helpers.GetMeterIfBelongsToUser(db, meterIdString);
            
            requestValid = (meter != null);
            if (requestValid)
            {
                meterId = meter.me_id;
                lblMeterName.Text = meter.me_meterName;
                meter.ElectricityDaily_Manual.Load();
                lblTotalInfo.Text = string.Format("Total electricity usage by year and month for meter '{0}'", meter.me_meterName);
                hypManageMeter.NavigateUrl = string.Format("~/meter/AddNewManual.aspx?meterId={0}", meter.me_meterGuid);


                if (!Page.IsPostBack)
                {


                    var startMonthString = Request.QueryString["monthStart"];
                    DateTime monthStartDate;
                    if (DateTime.TryParse(startMonthString, out monthStartDate))
                    {
                        LoadCharts(monthStartDate);
                    }
                    else
                    {

                        var startYearString = Request.QueryString["yearStart"];
                        DateTime yearStartDate;
                        if (DateTime.TryParse(startYearString, out yearStartDate))
                        {
                            LoadCharts(yearStartDate);
                        }
                        else
                        {
                            var lastReading = meter.ElectricityDaily_Manual.OrderByDescending(de => de.de_dateTime).FirstOrDefault();
                            LoadCharts(lastReading.de_dateTime);
                        }
                    }
                }
            }
        }
        else
        {
            requestValid = false;
        }
        panelNoAcccess.Visible = !requestValid;
        panelValid.Visible = requestValid;

    }

    

    void LoadCharts(DateTime startDate)
    {
        txtElectricityDate.Text = startDate.ToShortDateString();
        var trimmedDailyStartDate = new DateTime(startDate.Year, startDate.Month, 1);
        LoadDailyData(trimmedDailyStartDate);

        var trimmedMonthlyStartDate = new DateTime(startDate.Year, 1, 1);
        LoadMonthlyData(trimmedMonthlyStartDate);

        LoadAnnualData(trimmedMonthlyStartDate);

        LoadAnnualComparisons();
    }

    private void LoadDailyData(DateTime dayInMonth)
    {
        int month = dayInMonth.Month;
        int year = dayInMonth.Year;

        var meterReadings = meter.ElectricityDaily_Manual.Where(er => er.de_dateTime.Month == month && er.de_dateTime.Year == year);
        string title = string.Format("Daily Electricity usage for {0}", dayInMonth.ToString("MMM yyyy"));

        chartDaily.Titles[0].Text = title;
        lblMonth.Text = title;

        chartDaily.DataSource = meterReadings.ToList();

        // chartDaily.Series["Electricity"].Points.DataBindXY(meterReadings, "de_dateTime", meterReadings, "de_kWhDaily");
        chartDaily.DataBind();

    }

    private void LoadMonthlyData(DateTime dayInMonth)
    {
        int year = dayInMonth.Year;
        //var meterReadings = db.ElectricityMonthy_Manual.Where(er => er.YearStart == year && er.MeterId == meterId).OrderBy(er => er.MonthStart);

        var meterReadings = from e in meter.ElectricityDaily_Manual
                            where e.de_dateTime.Year == year
                            group e.de_kWhDaily by e.de_dateTime.Month into monthly
                            select new
                            {
                                Month = monthly.Key,
                                TotalKWh = monthly.Sum()
                            };
        chartMonthly.ChartAreas[0].AxisX.Minimum = 1;
        chartMonthly.ChartAreas[0].AxisX.Maximum = 12;
        chartMonthly.ChartAreas[0].AxisX.LabelStyle.Format = "{0:d}";
        chartMonthly.DataSource = meterReadings.ToList(); 
        // chartDaily.Series["Electricity"].Points.DataBindXY(meterReadings, "de_dateTime", meterReadings, "de_kWhDaily");
        chartMonthly.DataBind();

        string title = string.Format("Total monthly Electricity usage for {0}", year);

        chartMonthly.Titles[0].Text = title;


        var minDate = new DateTime(1900, 1, 1).AddDays(-2);
        foreach (Series series in chartMonthly.Series)
        {
            for (int pointIndex = 0; pointIndex < series.Points.Count; pointIndex++)
            {
                // string toolTip = "";
                ////  toolTip = "<IMG SRC=RegionChart.aspx?region=" + series.Points[pointIndex].AxisLabel + ">";
                // series.Points[pointIndex].MapAreaAttributes = "onmouseover=\"DisplayTooltip('" + toolTip + "');\" onmouseout=\"DisplayTooltip('');\"";


                //var date = minDate.AddDays(series.Points[pointIndex].XValue);
                var date = string.Format("{0}-{1}-1", year, series.Points[pointIndex].XValue);
                series.Points[pointIndex].Url = string.Format("MeterDaily.aspx?meterId={0}&monthStart={1}", meterId, date);
            }
        }
    }


    private void LoadAnnualData(DateTime dayInYear)
    {

        var meterReadings = from e in meter.ElectricityDaily_Manual
                         
                            group e.de_kWhDaily by e.de_dateTime.Year into annual
                            select new
                            {
                                Year = annual.Key,
                                TotalKWh = annual.Sum()
                            };

        chartAnnual.DataSource = meterReadings.ToList();
        // chartDaily.Series["Electricity"].Points.DataBindXY(meterReadings, "de_dateTime", meterReadings, "de_kWhDaily");
        chartAnnual.DataBind();
        var years = from y in meterReadings select y.Year;
        var minDate = years.Min();
        var maxDate = years.Max();

        StringBuilder title = new StringBuilder("Total annual electricity use, ").Append(minDate);
        if (minDate != maxDate)
        {
            title.Append("-").Append(maxDate);
        }
        chartAnnual.Titles[0].Text = title.ToString();


        foreach (Series series in chartAnnual.Series)
        {
            for (int pointIndex = 0; pointIndex < series.Points.Count; pointIndex++)
            {
                // string toolTip = "";
                ////  toolTip = "<IMG SRC=RegionChart.aspx?region=" + series.Points[pointIndex].AxisLabel + ">";
                // series.Points[pointIndex].MapAreaAttributes = "onmouseover=\"DisplayTooltip('" + toolTip + "');\" onmouseout=\"DisplayTooltip('');\"";


                //var date = minDate.AddDays(series.Points[pointIndex].XValue);
                var date = string.Format("{0}-1-1",  series.Points[pointIndex].XValue);
                series.Points[pointIndex].Url = string.Format("MeterDaily.aspx?meterId={0}&yearStart={1}", meterId, date);
            }
        }
    }

    void LoadAnnualComparisons()
    {


        var legendName = "YearLegend";
        chartCompareYearsByMonth.Legends.Add(new Legend(legendName));
        
        var years = from e in meter.ElectricityDaily_Manual
                    group e.de_kWhDaily by e.de_dateTime.Year into annual
                    select annual.Key;

        foreach (var year in years)
        {
            var seriesName = year.ToString();
            //meter.ElectricityDaily_Manual.Load();
            var meterReadings = from e in meter.ElectricityDaily_Manual
                                where e.de_dateTime.Year == year
                                group e.de_kWhDaily by e.de_dateTime.Month into monthly
                                select new
                                {
                                    Month = monthly.Key,
                                    TotalKWh = monthly.Sum()
                                };            
            Series series = chartCompareYearsByMonth.Series.Add(seriesName);
           
            series.Legend = legendName;
            foreach (var reading in meterReadings)
            {
                double[] convertedReading = {Convert.ToDouble(reading.TotalKWh)};
                var dateUrl = string.Format("{0}-{1}-1", year,reading.Month);
                var dateTooltip = string.Format("{0}-{1}, {2} kWh", MonthNumberToName(reading.Month), year, reading.TotalKWh);
                var url = string.Format("MeterDaily.aspx?meterId={0}&monthStart={1}", meterId, dateUrl);
                var newDataPointItem = new DataPoint { YValues = convertedReading, Url = url, ToolTip= dateTooltip };
                series.Points.Add(newDataPointItem);
               
            }

            series.ChartArea = "ChartArea1";
            series.ChartType = SeriesChartType.StackedColumn;
            series.BorderWidth = 2;
        }

        this.chartCompareYearsByMonth.Legends[legendName].IsDockedInsideChartArea = true;
        this.chartCompareYearsByMonth.Legends[legendName].Docking = Docking.Top;
        this.chartCompareYearsByMonth.Legends[legendName].DockedToChartArea = "ChartArea1";
    }

    string MonthNumberToName(int number)
    {
        DateTime tempDate = new DateTime(1900, number, 1);
        var monthName = tempDate.ToString("MMM");
        return monthName;
    }

    protected void Unnamed1_Click(object sender, EventArgs e)
    {

    }
    protected void btnFind_Click(object sender, EventArgs e)
    {
        var findDateString = txtElectricityDate.Text; ;
        DateTime findStartDate;
        if (DateTime.TryParse(findDateString, out findStartDate))
        {
            LoadCharts(findStartDate);
        }
        
    }
}
